#include <SDL/SDL.h>
#include <SDL/SDL_thread.h>
#include <GL/gl.h>
#include <stdio.h>

static int counter = 0;
SDL_mutex *counter_mutex;

// Flag to control the threads' execution.
static int exit_flag = 0;

int threadEntryPoint (void *data)
{
  char *threadname;

  threadname = (char*) data;

  // Loop until main() sets exit_flag.
  while (exit_flag == 0) {
      printf("This is %s!\n", threadname);

      // Get a lock on the counter variable.
      SDL_mutexP(counter_mutex);

      // Modify the counter safely.
      printf("The current counter is %i.\n", counter);
      counter++;

      // Release the lock.
      SDL_mutexV(counter_mutex);

      // Delay for a random amount of time.
      SDL_Delay(rand() % 3000);      
  }// End while.

  printf("%s is now exiting.\n", threadname);

  return 0;
}

int main ()
{
  SDL_Thread *thread1, *thread2, *thread3;

  // Create a mutex to protect the counter.
  counter_mutex = SDL_CreateMutex();

  // Create 3 threads.
  thread1 = SDL_CreateThread(threadEntryPoint, "Thread_1");
  thread2 = SDL_CreateThread(threadEntryPoint, "Thread_2");
  thread3 = SDL_CreateThread(threadEntryPoint, "Thread_3");

  // Let the threads run until counter reaches 20.
  while (counter < 20)
    SDL_Delay(1000);

  // Set the exit flag.
  exit_flag = 1;
  printf("Exit flag has been set by main().\n");
  
  // Wait for the threads to terminate.
  SDL_Delay(3500);
  
  // Destroy the counter mutex.
  SDL_DestroyMutex(counter_mutex);

  return 0;
}
